﻿package com.kucooler.fog.model {
	import com.kucooler.fog.core.MvcLocator;
	import com.kucooler.fog.utils.mvcError;
	import com.kucooler.fog.utils.PaperLogger;
	/**
	 * 单例模式的数据集合
	 * <p>
	 * <ul>
	 * <li>保存所有model对象的引用</li>
	 * <li>具有model对象的添加、删除、获取等操作</li>
	 * </ul>
	 * </p>
	 */
	public class ModelLocator extends MvcLocator implements IModelLocator {
		static private var m_instance:IModelLocator = null;
		
		public function ModelLocator() {
			if (m_instance != null) {
				throw new mvcError(mvcError.SINGLETON_MODEL_MSG, ModelLocator);
			}
		}
		
		static public function getInstance():IModelLocator {
			if (m_instance == null) {
				m_instance = new ModelLocator();
			}
			return m_instance;
		}
		
		/**
		 * 取回模型
		 * @param	modelName Class		模型类
		 * @return *					当前模型实例
		 */
		public function getModel(modelName:Class):* {
			if (!hasExists(modelName)) {
				PaperLogger.getInstance().log(mvcError.MODEL_NOT_FOUND, ModelLocator, modelName);
			}
			return retrieve(modelName);
		}
		
		/**
		 * 添加模型
		 * @param	modelName Class		模型类
		 * @param	data Object			当前模型构造函数的参数
		 */
		public function addModel(modelName:Class, data:Object = null):void {
			if (!hasExists(modelName)) {
				if (data != null) {
					add(modelName, new modelName(data));
				}else {
					add(modelName, new modelName());
				}
			}else {
				PaperLogger.getInstance().log(mvcError.ADD_MODEL_MSG, ModelLocator, modelName);
			}
		}
		
		/**
		 * 移除模型
		 * @param	modelName Class  	模型类
		 */
		public function removeModel(modelName:Class):void {
			if (hasExists(modelName)) {
				var _model = retrieve(modelName);
				_model.destroy();
				remove(modelName);
			}else {
				PaperLogger.getInstance().log(mvcError.REMOVE_MODEL_MSG, ModelLocator, modelName);
			}
		}
		
		/**
		 * 判断此模型是否已经存在
		 * @param	modelName Class  	模型类
		 * @return  Boolean 			是否存在
		 */
		public function hasModel(modelName:Class):Boolean {
			return hasExists(modelName);
		}
	}
}
